package com.usian.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.usian.common.constant.behavior.FollowBehaviorConstants;
import com.usian.common.constant.wmnews.NewAutoScanConstants;
import com.usian.model.article.dtos.ApUserDto;
import com.usian.model.article.pojos.ApAuthor;
import com.usian.model.behavior.dtos.FollowBehaviorDto;
import com.usian.model.common.dtos.ResponseResult;
import com.usian.model.common.enums.AppHttpCodeEnum;
import com.usian.model.user.dtos.UserRelationDto;
import com.usian.model.user.pojos.ApUser;
import com.usian.model.user.pojos.ApUserFan;
import com.usian.model.user.pojos.ApUserFollow;
import com.usian.user.feign.ArticleFeign;
import com.usian.user.mapper.ApUserFanMapper;
import com.usian.user.mapper.ApUserFollowMapper;
import com.usian.user.mapper.ApUserMapper;
import com.usian.user.service.ApUserFanService;
import com.usian.user.service.ApUserFollowService;
import com.usian.user.service.ApUserService;
import com.usian.utils.common.AppJwtUtil;
import com.usian.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;

/**
 * ClassName: ApUserServiceImpl
 * Author:   WGG
 * Date:    2022-11-2022/11/30-11:26
 * Version: 1.0
 * Description:
 */
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper,ApUser> implements ApUserService {

    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Autowired
    private ArticleFeign articleFeign;

    @Resource
    private ApUserFollowMapper apUserFollowMapper;

    @Resource
    private ApUserFanMapper apUserFanMapper;

    @Resource
    private ApUserMapper apUserMapper;

    @Override
    public ResponseResult login(ApUserDto dto) {
        //校验参数是否为空
        if (dto.getEquipmentId()==null && (dto.getPassword()==null&&dto.getName()==null)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //1.登录通过
        if (dto.getPassword()!=null||dto.getName()!=null){
            //根据用户名查询数据
            ApUser apUser = getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getName, dto.getName()));
            if (apUser==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
            }else {
                //md5加密
                String password = DigestUtils.md5DigestAsHex((dto.getPassword()+apUser.getSalt()).getBytes());
                //校验密码是否正确
                if (!password.equals(apUser.getPassword())){
                    return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
                }else {
                    //携带token通过
                    HashMap<String, Object> map = new HashMap<>();
                    apUser.setPassword("");
                    apUser.setSalt("");
                    map.put("token", AppJwtUtil.getToken(apUser.getId().longValue()));
                    map.put("user",apUser);
                    return ResponseResult.okResult(map);
                }

            }
        }else {
            //2.非登录通过
            if (dto.getEquipmentId()==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
            }
            //携带token通过
            HashMap<String, Object> map = new HashMap<>();
            map.put("token", AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(map);
        }

    }

    @Override
    public ResponseResult userFollow(UserRelationDto dto) {
        //判断参数是否为空
        if (dto==null && dto.getAuthorId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //根据作者id拿到作者信息
        ApAuthor apAuthor = articleFeign.findById(dto.getAuthorId());
        Integer followId=null;
        //如果作者信息不为空
        if (apAuthor!=null){
            followId=apAuthor.getId();
        }
        //判断token信息是否正确
        ApUser apUser = AppThreadLocalUtils.getUser();
        Integer userId = apUser.getId();
        if (userId==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.TOKEN_INVALID);
        }
        ResponseResult r = new ResponseResult();
        if (dto.getOperation()==1){
            //1.关注 operation=0
            r = follow(followId, apAuthor, userId);
            FollowBehaviorDto followBehaviorDto = new FollowBehaviorDto();
            followBehaviorDto.setArticleId(dto.getArticleId());
            followBehaviorDto.setFollowId(followId);
            followBehaviorDto.setUserId(userId);

            kafkaTemplate.send(FollowBehaviorConstants.FOLLOW_BEHAVIOR_TOPIC, JSON.toJSONString(followBehaviorDto));
        }else{
            //2.取消operation=1
            r=cancel(followId,apAuthor,userId);
        }
        return r;
    }

    @Override
    public ApUser findById(Long id) {
        return getOne(Wrappers.<ApUser>lambdaQuery().eq(ApUser::getId,id));
    }

    //关注
    public ResponseResult follow(Integer followId, ApAuthor apAuthor, Integer userId){
        if (followId!=null){
            //判断用户粉丝信息是否存在
            ApUserFollow apUserFollow = apUserFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery().eq(ApUserFollow::getFollowId, followId).eq(ApUserFollow::getUserId, userId));
            if (apUserFollow==null){
                //如果为空添加数据
                //添加app用户关注信息表 ap_user_follow
                ApUserFollow apUserFollow1 = new ApUserFollow();
                apUserFollow1.setCreatedTime(new Date());
                apUserFollow1.setFollowId(followId);
                apUserFollow1.setFollowName(apAuthor.getName());
                apUserFollow1.setUserId(userId);
                apUserFollow1.setLevel(1);
                apUserFollow1.setIsNotice(true);
                apUserFollowMapper.insert(apUserFollow1);
                //判断用户关注信息是否存在 user_id 是用户id这个用户是身为作者author的用户 fans_id是当前登录设备的用户信息
                ApUserFan apUserFan = apUserFanMapper.selectOne(Wrappers.<ApUserFan>lambdaQuery().eq(ApUserFan::getUserId, apAuthor.getUserId()).eq(ApUserFan::getFansId, userId));
                if (apUserFan==null){
                    //如果为空添加数据
                    //添加app用户粉丝信息表 ap_user_fan
                    ApUserFan apUserFan1 = new ApUserFan();
                    apUserFan1.setCreatedTime(new Date());
                    apUserFan1.setFansId(userId);
                    ApUser apUser = apUserMapper.selectById(userId);
                    apUserFan1.setFansName(apUser.getName());
                    apUserFan1.setUserId(apAuthor.getUserId());
                    apUserFan1.setLevel(0);
                    apUserFan1.setIsDisplay(true);
                    apUserFan1.setIsShieldComment(false);
                    apUserFan1.setIsShieldLetter(false);
                    apUserFanMapper.insert(apUserFan1);
                }
            }
        }
        return ResponseResult.okResult(AppHttpCodeEnum.DATA_EXIST);
    }
    //取消
    public ResponseResult cancel(Integer followId, ApAuthor apAuthor, Integer userId){
        //删除app用户关注信息表 ap_user_follow
        ApUserFollow apUserFollow = apUserFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery().eq(ApUserFollow::getFollowId, followId).eq(ApUserFollow::getUserId, userId));
        if (apUserFollow!=null){
            System.out.println(apUserFollow.getId());
            apUserFollowMapper.deleteById(apUserFollow.getId());
        }
        //删除app用户粉丝信息表 ap_user_fan
        ApUserFan apUserFan = apUserFanMapper.selectOne(Wrappers.<ApUserFan>lambdaQuery().eq(ApUserFan::getUserId, apAuthor.getUserId()).eq(ApUserFan::getFansId, userId));
        if (apUserFan!=null){
            System.out.println(apUserFan.getId());
            apUserFanMapper.deleteById(apUserFan.getId());
        }
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

}
